package com.springboot.framework.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.springboot.framework.enums.Errors;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.OrderModel;
import com.springboot.framework.service.OrderService;
import com.springboot.framework.service.PayService;
import com.springboot.framework.utils.ResponseVoUtil;
import com.springboot.framework.vo.ResponseVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;

/**
 * @author SWF
 * @date 2019/6/18 13:26
 **/
@Api(description = "支付")
@RestController
@RequestMapping("/pay")
public class PayController {

    @Resource
    private WxPayService wxPayService;

    @Resource
    private OrderService orderService;



    @RequestMapping(value = "wxpay")
    public ResponseVO<Object> pay(@RequestParam String openId,@RequestParam String orderId) {
        OrderModel orderModel = orderService.get(orderId);
        if(orderModel == null){
            throw new BusinessException(Errors.ORDER_NOT_EXIST);
        }
        if(!orderModel.getUserWechatOpenid().equals(openId)){
            throw new BusinessException(Errors.ORDER_NOT_EXIST);
        }

       return null;
    }

    @ResponseBody
    @RequestMapping("/wx")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            // 结果正确
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
           // log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
}
